﻿using System;
using System.Collections.Generic;
using System.Management;
using System.Reflection;

using DreamCube.Foundation.Basic.Utility;

namespace DreamCube.Foundation.WMI
{
    /// <summary>
    /// 获取WMI信息的的基础类
    /// </summary>
    /// <typeparam name="TModel"></typeparam>
    public abstract class ManagementClassBasic<TModel> where TModel : class,new()
    {
        #region "属性"

        /// <summary>
        /// 对应的WMI类名
        /// </summary>
        public abstract String ClassName
        { get; }

        #endregion

        #region "公共方法"

        public virtual List<TModel> GetModels()
        {
            if (String.IsNullOrEmpty(ClassName)) throw new ArgumentNullException();
            ManagementObjectSearcher objs =
                new ManagementObjectSearcher(String.Format("select * from {0}", this.ClassName));
            List<TModel> models = new List<TModel>();
            foreach (ManagementObject obj in objs.Get())
            {
                TModel model = new TModel();
                SetModelValue(model, obj);
                models.Add(model);
            }
            return models;
        }

        #endregion

        #region "私有方法"

        /// <summary>
        /// 设置硬盘的属性值
        /// </summary>
        /// <param name="model"></param>
        /// <param name="?"></param>
        protected static void SetModelValue(Object model, ManagementObject obj)
        {
            Dictionary<PropertyInfo, ManagementObjectPropertyMappingAttribute> vals =
                MyType.GetAttributesOfProperties<ManagementObjectPropertyMappingAttribute>(model, false);
            foreach (KeyValuePair<PropertyInfo, ManagementObjectPropertyMappingAttribute> item in vals)
            {
                Object val = null;
                try
                {
                    if (item.Value.ConvertDataFun != null)
                        val = item.Value.ConvertDataFun.Invoke(obj[item.Value.ManagementObjectPropertyName]);
                    else
                        val = obj[item.Value.ManagementObjectPropertyName];
                }
                catch (Exception)
                { }
                if (val != null) MyReflection.SetPropertyValue(item.Key.Name, model, val);
            }
        }

        #endregion
    }
}
